<template>
  <div class="app-container calendar-list-container">
    <basic-container>
      <template>
        <el-tabs @tab-click="switchTab">
          <el-tab-pane label='信息管理' name='userManager'/>
          <el-tab-pane label='安全管理' name='passwordManager'/>
        </el-tabs>
      </template>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form :model="ruleForm2"
                     :rules="rules2"
                     ref="ruleForm2"
                     label-width="100px"
                     v-if="switchStatus==='userManager'"
                     class="demo-ruleForm">
              <el-form-item label="头像"
                            prop="avatar">
                  <el-upload
                    class="avatar-uploader"
                    :action="actionUrl"
                    :headers="headers"
                    :limit="1"
                    :show-file-list="false"
                    :on-success="handleUploadSuccess"
                    :before-upload="beforeImageUpload">
                    <img v-if="ruleForm2.avatar" :src="ruleForm2.avatar" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
              </el-form-item>
              <el-form-item label="用户名"
                            prop="username">
                <el-input type="text"
                          v-model="ruleForm2.username"
                          disabled></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="ruleForm2.gender">
                  <span v-for="i in genderDict" style="margin-right: 10px">
                  <el-radio  :label="i.value" >{{i.label}}</el-radio>
                  </span>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm2.email" placeholder="邮箱"></el-input>
              </el-form-item>
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="ruleForm2.birthday"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="籍贯" prop="province">
                <el-input v-model="ruleForm2.province" placeholder="请输入籍贯"></el-input>
              </el-form-item>

              <el-form-item label="手机号" prop="mobile">
                <el-input v-model="ruleForm2.mobile" placeholder="验证码登录使用"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"
                           @click="submitForm('ruleForm2')">提交
                </el-button>
                <el-button @click="resetForm('ruleForm2')">重置</el-button>
              </el-form-item>
            </el-form>
            <el-form :model="ruleForm2"
                     :rules="rules2"
                     ref="ruleForm2"
                     label-width="100px"
                     v-if="switchStatus==='passwordManager'"
                     class="demo-ruleForm">
              <el-form-item label="原密码"
                            prop="password">
                <el-input type="password"
                          v-model="ruleForm2.password"
                          auto-complete="off"></el-input>

              </el-form-item>
              <el-form-item label="密码"
                            prop="newpassword1">
                <el-input type="password"
                          v-model="ruleForm2.newpassword1"
                          auto-complete="off"></el-input>
                <div class="prefixCls-bar">
                  <div class="prefixCls-bar--fill" :data-score="getPasswordStrength"></div>
                </div>
              </el-form-item>
              <el-form-item label="确认密码"
                            prop="newpassword2">
                <el-input type="password"
                          v-model="ruleForm2.newpassword2"
                          auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"
                           @click="submitForm('ruleForm2')">提交
                </el-button>
                <el-button @click="resetForm('ruleForm2')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>


<script>
  import {isvalidatemobile, verifyPasswordStrength} from "@/util/validate";
  import {getAttInfo} from "@/api/admin/user";
  import {remote} from '@/api/admin/dict'
  import {mapState} from 'vuex'
  import store from "@/store";
  import request from '@/router/axios'

  export default {
    data() {
      var validatePhone = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]));
        } else {
          callback();
        }
      };
      var validatePass = (rule, value, callback) => {
        if (this.ruleForm2.password !== '') {
          if (value !== this.ruleForm2.newpassword1) {
            callback(new Error('两次输入密码不一致!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        switchStatus: '',
        actionUrl:'/admin-service/file/upload',
        show: false,
        headers: {
          Authorization: 'Bearer ' + store.getters.access_token
        },
        genderDict:[],
        userAtt:null,
        ruleForm2: {
          username: '',
          password: '',
          newpassword1: '',
          newpassword2: '',
          avatar: '',
          gender: '',
          birthday: '',
          email: '',
          province: '',
          mobile: ''
        },
        rules2: {
          password: [{required: true, min: 6, message: '原密码不能为空且不少于6位', trigger: 'change'}],
          mobile: [{required: true, validator: validatePhone, trigger: 'change'}],
          newpassword1: [{required: false, min: 6, message: '不少于6位', trigger: 'change'}],
          newpassword2: [{required: false, validator: validatePass, trigger: 'blur'}],
          email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]
        }
      }
    },
    created() {
      this.ruleForm2.username = this.userInfo.username;
      this.ruleForm2.mobile = this.userInfo.mobile;
      this.ruleForm2.email = this.userInfo.email;
      this.switchStatus = 'userManager';
      this.remoteDictType();
      this.getAttInfoHandle();
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo
      }),
      getPasswordStrength(){
        return verifyPasswordStrength(this.ruleForm2.newpassword1);
      }
    },
    methods: {
      remoteDictType(){
        remote('gender').then(res=>{
          this.genderDict = res.data.data;
        })
      },
      getAttInfoHandle(){
        getAttInfo().then(res=>{
          this.userAtt = res.data.data;
          this.ruleForm2.avatar = this.userAtt.avatar;
          this.ruleForm2.gender = this.userAtt.gender?this.userAtt.gender:'3';
          this.ruleForm2.birthday = this.userAtt.birthday;
          this.ruleForm2.province = this.userAtt.province;
        })
      },
      switchTab(tab, event) {
        this.switchStatus = tab.name;
        this.$refs['ruleForm2'].clearValidate();
      },
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            request({
              url: '/admin-service/user/edit',
              method: 'put',
              data: this.ruleForm2
            }).then(response => {
              if (response.data.data) {
                this.$notify({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                // 修改密码之后强制重新登录
                if (this.switchStatus === 'passwordManager') {
                  this.$store.dispatch('LogOut').then(() => {
                    location.reload() // 为了重新实例化vue-router对象 避免bug
                  })
                }
              } else {
              }
            }).catch(() => {
            })
          } else {
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      beforeImageUpload(file) {
        const isType = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp' || file.type === 'image/jpg';
        const isLt = file.size / 1024 / 1024 < 2;
        if (!isType) {
          this.$message.error('上传图片格式不对!');
        }
        if (!isLt) {
          this.$message.error('上传图片大小不能超过2M!');
        }
        return isType && isLt;
      },
      handleUploadSuccess(response, file, fileList) {
        if (response.code == 200) {
          this.ruleForm2.avatar = response.data.url;
        } else {
          this.$message.error('上传出错：' + response.data.msg)
        }
      },
    }
  }
</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px!important;
    color: #8c939d!important;
    width: 178px!important;
    height: 178px!important;
    line-height: 178px!important;
    text-align: center!important;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style scoped lang="scss">
  .prefixCls {
    &-bar {
      position: relative;
      height: 6px;
      margin: 10px auto 6px;
      background-color: grey;
      border-radius: 6px;

      &::before,
      &::after {
        position: absolute;
        z-index: 10;
        display: block;
        width: 33%;
        height: inherit;
        background-color: transparent;
        border-color: white;
        border-style: solid;
        border-width: 0 5px;
        content: '';
      }

      &::before {
        left: 33%;
      }

      &--fill {
        position: absolute;
        width: 0;
        height: inherit;
        background-color: transparent;
        border-radius: inherit;
        transition: width 0.5s ease-in-out, background 0.25s;

        &[data-score='1'] {
          width: 33%;
          background-color: red;
        }

        &[data-score='2'] {
          width: 67%;
          background-color: yellow;
        }

        &[data-score='3'] {
          width: 100%;
          background-color: green;
        }
      }
    }
  }
</style>
